import React, { useEffect, useRef, useState } from "react";
import {
    Scene,
    PerspectiveCamera,
    WebGLRenderer,
    BoxGeometry,
    Mesh,
    MeshStandardMaterial,
    TextureLoader,
    DoubleSide,
    AmbientLight,
    DirectionalLight,
} from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

interface ThreeSceneProps {
    imgList: string[]; // 图片数组
}

const ThreeScene: React.FC<ThreeSceneProps> = ({ imgList }) => {
    const containerRef = useRef<HTMLDivElement | null>(null);
    const sceneRef = useRef<Scene>(new Scene());
    const cameraRef = useRef<PerspectiveCamera>(
        new PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)
    );
    const rendererRef = useRef<WebGLRenderer>(new WebGLRenderer({ antialias: true }));
    const cubeRef = useRef<Mesh | null>(null);
    const controlsRef = useRef<OrbitControls | null>(null);

    // 初始化场景
    useEffect(() => {
        if (!containerRef.current) return;

        // 设置相机
        cameraRef.current.position.set(0, 0, 5);
        cameraRef.current.lookAt(sceneRef.current.position);

        // 设置渲染器
        rendererRef.current.setSize(window.innerWidth, window.innerHeight);
        rendererRef.current.setClearColor(0x000000);
        containerRef.current.appendChild(rendererRef.current.domElement);

        // 添加灯光
        const ambientLight = new AmbientLight(0x404040, 1);
        sceneRef.current.add(ambientLight);

        const directionalLight1 = new DirectionalLight(0xffffff, 2);
        directionalLight1.position.set(1, 0, 0).normalize();
        directionalLight1.castShadow = true;
        sceneRef.current.add(directionalLight1);

        const directionalLight2 = new DirectionalLight(0xffffff, 2);
        directionalLight2.position.set(-1, 0, 0).normalize();
        directionalLight2.castShadow = true;
        sceneRef.current.add(directionalLight2);

        const directionalLight3 = new DirectionalLight(0xffffff, 2);
        directionalLight3.position.set(0, -1, 0).normalize();
        directionalLight3.castShadow = true;
        sceneRef.current.add(directionalLight3);

        const directionalLight4 = new DirectionalLight(0xffffff, 2);
        directionalLight4.position.set(0, 0, -1).normalize();
        directionalLight4.castShadow = true;
        sceneRef.current.add(directionalLight4);

        const directionalLight5 = new DirectionalLight(0xffffff, 2);
        directionalLight5.position.set(0, 1, 0).normalize();
        directionalLight5.castShadow = true;
        sceneRef.current.add(directionalLight5);

        const directionalLight6 = new DirectionalLight(0xffffff, 2);
        directionalLight6.position.set(0, 0, 1).normalize();
        directionalLight6.castShadow = true;
        sceneRef.current.add(directionalLight6);


        // 添加轨道控制器
        controlsRef.current = new OrbitControls(cameraRef.current, rendererRef.current.domElement);
        controlsRef.current.enableDamping = true;
        controlsRef.current.dampingFactor = 0.25;

        // 窗口大小调整事件
        const onWindowResize = () => {
            cameraRef.current.aspect = window.innerWidth / window.innerHeight;
            cameraRef.current.updateProjectionMatrix();
            rendererRef.current.setSize(window.innerWidth, window.innerHeight);
        };
        window.addEventListener("resize", onWindowResize);

        // 清理函数
        return () => {
            window.removeEventListener("resize", onWindowResize);
            containerRef.current?.removeChild(rendererRef.current.domElement);
        };
    }, []);

    // 根据图片数组生成材质
    useEffect(() => {
        if (!imgList.length) return;

        const textureLoader = new TextureLoader();
        const materials = imgList.map((img,index) => {
            const texture = textureLoader.load(img,(texture) => {
                if (index === 2) {
                    texture.rotation = Math.PI;
                    texture.center.set(0.5, 0.5);
                }
                if (index === 3) {
                    texture.rotation = -Math.PI;
                    texture.center.set(0.5, 0.5);
                }
            });
            return new MeshStandardMaterial({ map: texture, side: DoubleSide });
        });

        // 移除旧的立方体
        if (cubeRef.current) {
            sceneRef.current.remove(cubeRef.current);
            cubeRef.current.geometry.dispose();
            (Array.isArray(cubeRef.current.material) ? cubeRef.current.material : [cubeRef.current.material]).forEach((mat) => mat.dispose());
        }

        // 创建新的立方体
        const geometry = new BoxGeometry(10, 10, 10);
        const cube = new Mesh(geometry, materials);
        cube.position.set(0, 0, 0);
        sceneRef.current.add(cube);
        cubeRef.current = cube;
    }, [imgList]);

    // 渲染循环
    useEffect(() => {
        const animate = () => {
            requestAnimationFrame(animate);
            controlsRef.current?.update();
            rendererRef.current.render(sceneRef.current, cameraRef.current);
        };
        animate();
    }, []);

    return <div ref={containerRef} style={{ width: "100%", height: "100vh" }} />;
};

export default ThreeScene;